﻿using clf.weighing.entity;
using HandyControl.Controls;
using MyHelper;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace weighing
{
    /// <summary>
    /// CompanyInitWindow.xaml 初始化使用单位 的交互逻辑
    /// </summary>
    public partial class CompanyInitWindow : GlowWindow
    {
        #region variables
        private bool isInited = false; //是否已经保存，初始化。
        private Company? mCompany;
        /// <summary>
        /// 数据库存已经存在的公司信息
        /// </summary>
        private Company? OldCompany;
        #endregion


        public CompanyInitWindow()
        {
            InitializeComponent();

            CommonFunction.ShowCustomIcon(this);
        }
        private void InitCompanyWiondow_ContentRendered(object sender, EventArgs e)
        {
            mCompany = CompanyDao.Instance.FindById(Convert.ToInt64(App.InitConfig.companyId));
            if (mCompany != null)
            {
                this.DataContext = new CompanyVo(mCompany);
                this.skipBtn.Visibility = Visibility.Collapsed;
                this.alertTb.Text = "已经初始化过谨慎操作";              
            }
        }
        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (mCompany != null)
            {
                Update();
            }
            else
            {
                FirstInsert();
            }
        }


        private void FirstInsert()
        {
            Company company;
            if (mCompany != null)
            {
                company = mCompany;
            }
            else
            {
                company = new Company();
            }
            company.fullName = this.nameTb.Text.Trim();
            if (company.fullName.IsNullOrEmpty() || !company.fullName.Length.IsBetween(2, 30))
            {
                this.saveBtn.IsChecked = false;
                Growl.Info("公司全称的长度为2到30 个字之间");
                return;
            }
            company.nameFirstCase = StringHelper.GetFirstPinyin(company.fullName);

            company.shortName = this.shortNameTb.Text.Trim();
            if (company.shortName.IsNullOrEmpty() || !company.shortName.Length.IsBetween(2, 30))
            {
                this.saveBtn.IsChecked = false;
                Growl.Info("公司简称的长度为2到10 个字之间");
                return;
            }

            company.connectPeople = this.connectPeopleTb.Text.Trim();

            company.connectPhone = this.phoneTb.Text.Trim();

            int res;
            if (mCompany != null)
            {
                company.legalPerson = this.legalPersonTb.Text.Trim();
                company.updateTime = DateTime.Now;
                company.updateUserId = company.addUserId;
                company.updateUserName = company.addUserName;
                res = CompanyDao.Instance.Sqlite.Update(company);
            }
            else
            {
                company.id = IdHelper.LongID;
                company.legalPerson = this.legalPersonTb.Text.Trim();
                if (App.CurrentUser == null)
                {
                    company.addUserId = 1;
                    company.addUserName = "admin";
                }
                else
                {
                    company.addUserId = App.CurrentUser.id;
                    company.addUserName = App.CurrentUser.name;
                }
                company.updateTime = DateTime.Now;
                company.addTime = company.updateTime;
                company.updateUserId = company.addUserId;
                company.updateUserName = company.addUserName;
                company.isCoalSource = 0;
                company.isDelete = 0;
                res = CompanyDao.Instance.InitCompany(company);
                if (res > 0)
                {
                    //0.更新 InitConfig            
                    App.InitConfig.companyId = company.id;
                    App.InitConfig.companyName = company.fullName;
                    Debug.WriteLine(App.InitConfig);
                    InitConfigDao.Instance.Sqlite.Update(App.InitConfig);
                }
            }

            if (res > 0)
            {
                this.saveBtn.IsChecked = false;
                Growl.SuccessGlobal("初始化成功！");
                App.CurrentCompanyVo = new CompanyVo(company);
                DelegeteFactory.Instance.onUserCompanyChanged?.Invoke(App.CurrentCompanyVo);

                isInited = true;
                this.Close();
            }
            else
            {
                this.saveBtn.IsChecked = false;
                string msg = "保存数据失败！";
                Growl.Error(msg);
                this.alertTb.Text = msg;
            }
        }

        private void Update()
        {
            if(mCompany == null) return;
            string fn = this.nameTb.Text;
            if (!string.IsNullOrEmpty(fn)) {

                mCompany.fullName = fn;
                mCompany.nameFirstCase = StringHelper.GetAllSpell(fn);
            }
            string sn = this.shortNameTb.Text;
            if (!string.IsNullOrEmpty(sn)) { 
                mCompany.shortName = sn;
            }
            string legal = this.legalPersonTb.Text;
            if (!string.IsNullOrEmpty(legal)) {
                mCompany.legalPerson = legal;
            }
            string people = this.connectPeopleTb.Text;
            if (!string.IsNullOrEmpty(people))
            {
                mCompany.connectPeople = people;
            }
            string phone = this.phoneTb.Text;
            if (!string.IsNullOrEmpty(phone))
            {
                mCompany.connectPhone = phone;
            }
            mCompany.updateTime = DateTime.Now;
            mCompany.updateUserId = App.CurrentUser?.Id ?? 0;
            mCompany.updateUserName = App.CurrentUser?.name ?? "";

            var res = CompanyDao.Instance.Sqlite.Update(mCompany);

            if (res > 0)
            {
                this.saveBtn.IsChecked = false;
                Growl.SuccessGlobal("初始化成功！");
                App.CurrentCompanyVo = new CompanyVo(mCompany);
                isInited = true;
                DelegeteFactory.Instance.onUserCompanyChanged?.Invoke(App.CurrentCompanyVo);
                try
                {
                    //0.更新 InitConfig            
                    //App.InitConfig.companyId = mCompany.id;
                    App.InitConfig.companyName = mCompany.fullName;
                    Debug.WriteLine(App.InitConfig);
                    InitConfigDao.Instance.Sqlite.Update(App.InitConfig);
                }
                catch (Exception e)
                {
                    Log.Error("初始化公司更新 InitConfig失败：   " + e.Message);
                }            
                this.Close();
            }
            else
            {
                this.saveBtn.IsChecked = false;
                string msg = "保存数据失败！";
                Growl.Error(msg);
                this.alertTb.Text = msg;
            }
        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            ResertInput();
        }

        private void ResertInput()
        {
            this.saveBtn.IsChecked = false;
            this.nameTb.Text = "";
            this.shortNameTb.Text = "";
            this.legalPersonTb.Text = "";
            this.connectPeopleTb.Text = "";
            this.phoneTb.Text = "";
        }

        private void InitCompanyWiondow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.saveBtn.IsEnabled== true && !isInited)
            {
                var resultt = CommonFunction.Ask("您还未初始化成功，是否要退出？");
                if (resultt == MessageBoxResult.Yes)
                {
                   
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        //跳过
        private void SkipBtn_Click(object sender, RoutedEventArgs e)
        {
            string companyName = "未知使用公司";
            Company company = new()
            {
                id = IdHelper.LongID,
                legalPerson = "未知",
                updateTime = DateTime.Now,
                fullName = companyName,
                shortName = "未知",
                nameFirstCase = StringHelper.GetFirstPinyin(companyName),
                addTime = DateTime.Now,
                isCoalSource = 0,
                isDelete = 0
            };
            if (App.CurrentUser == null)
            {
                company.addUserId = 1;
                company.addUserName = "admin";
            }
            else
            {
                company.addUserId = App.CurrentUser.id;
                company.addUserName = App.CurrentUser.name;
            }

            int res = CompanyDao.Instance.InitCompany(company);
            if (res > 0)
            {
                //0.更新 InitConfig            
                App.InitConfig.companyId = company.id;
                App.InitConfig.companyName = company.fullName;
                InitConfigDao.Instance.Sqlite.Update(App.InitConfig);

                this.saveBtn.IsChecked = false;
                Growl.SuccessGlobal("初始化成功！");
                App.CurrentCompanyVo = new CompanyVo(company);
                isInited = true;
                this.Close();
            }
            else
            {
                Growl.Error("初始化失败！");
            }
        }
    }
}
